package com.macbulldev.poc.testgin.controller;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.Rate;
import com.macbulldev.poc.testgin.domain.StateOrProvince;
import com.macbulldev.poc.testgin.domain.Tier;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "tier", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.Tier.class)
@org.springframework.web.bind.annotation.RequestMapping("/tier/**")
@org.springframework.stereotype.Controller
public class TierController {
	
	
	private static final Logger LOGGER = Logger.getLogger(Tier.class);
	
	@RequestMapping(value = "/tier/list", method = RequestMethod.GET)    
    public String renderTierList(@RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {    

		
		int sizeNo = 20;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("tiers",Tier.findTierEntries(pageNumber*sizeNo, sizeNo));            
        Long count = Tier.countTiers();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        return "tier/list";        
    }
	
	@RequestMapping(value = "/tier/create_wizard", method = RequestMethod.GET)    
    public String renderTierCreateWizard(ModelMap modelMap) {    
        
		modelMap.addAttribute("tier", new Tier());  
		modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());
		
        return "tier/create_wizard";        
    }
	/*
	@RequestMapping(value = "/tier/ajax/{stateorprovinceId}", method = RequestMethod.GET)    
	public String renderTierCreateFormAjax(@PathVariable("stateorprovinceId") Long stateOrProvinceId,ModelMap modelMap) {    
		
		
		modelMap.addAttribute("tier", new Tier());        
        modelMap.addAttribute("rates", Rate.findRatesByStateOrProvince(stateOrProvinceId));
		
		
		return "tier/ajax_create";        
	}
	*/
	
	
	@RequestMapping(value = "/tier/ajax/create_wizard", method = RequestMethod.POST)      
    public String processTierCreateWizard(@RequestParam(value="isFlatCharge", required=false) String isFlat,ModelMap modelMap,Tier tier,@RequestParam(value = "rateid", required = false) Long rateid,HttpSession hs) 
	{  
		LOGGER.error("Create Tiers");
		String retMsg = "1";
		
		LOGGER.debug("isFlat:  "+isFlat);
		
		LOGGER.error(tier.getIsFlatCharge()+":"+rateid+":"+tier.getTierLowerAmt()+":"+tier.getTierUpperAmt()+":"+tier.getTierAddAmt()+":"+tier.getSubtractAmt()+":"+tier.getTierDivideAmt()+":"+tier.getTierMultiplyAmt());
		
		if(isFlat.equalsIgnoreCase("true"))
		{
			tier.setIsFlatCharge(true);
		}
		else
		{
			tier.setIsFlatCharge(false);
		}
		
		
		tier.setStateOrProvince(Rate.findRate(rateid).getStateOrProvince());
		tier.setRate(Rate.findRate(rateid));
		tier.setCreateTs(new Date());
		tier.setUpdateTs(new Date());
		AppUser sessionUser = WebappUtils.getAuthenticationObject(hs);
    	tier.setCreateUsername(sessionUser.getName());
    	tier.setUpdateUsername(sessionUser.getName());
    	tier.persist();
    	
    
		
		
    	modelMap.addAttribute("msg", retMsg);  
		return "tier/ajax_success"; 
		
	}
	
	@RequestMapping(value = "/tier/ajax/delete_all", method = RequestMethod.POST)    
    public String processDeleteAll(ModelMap modelMap,@RequestParam(value = "rateid", required = false) Long rateid) {    
       
		String retMsg = "1";
		LOGGER.error("Deleting Tiers");
		for(Tier tier : Tier.findTiersByRate(rateid))
		{
			tier.remove();
		}
		
		
		modelMap.addAttribute("msg", retMsg);  
		return "tier/ajax_success";       
    }
		

	@RequestMapping(value = "/tier", method = RequestMethod.POST)    
    public String create(@Valid Tier tier, BindingResult result, ModelMap modelMap) {    
        if (tier == null) throw new IllegalArgumentException("A tier is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("tier", tier);            
            modelMap.addAttribute("rates", Rate.findAllRates());            
            return "tier/create";            
        }        
        tier.persist();        
        return "redirect:/tier/" + tier.getId();        
    }

	@RequestMapping(value = "/tier/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("tier", new Tier());        
        modelMap.addAttribute("rates", Rate.findAllRates());        
        return "tier/create";        
    }

	@RequestMapping(value = "/tier/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("tier", Tier.findTier(id));        
        return "tier/show";        
    }

	@RequestMapping(value = "/tier", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("tiers", Tier.findTierEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) Tier.countTiers() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("tiers", Tier.findAllTiers());            
        }        
        return "tier/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid Tier tier, BindingResult result, ModelMap modelMap) {    
        if (tier == null) throw new IllegalArgumentException("A tier is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("tier", tier);            
            modelMap.addAttribute("rates", Rate.findAllRates());            
            return "tier/update";            
        }        
        tier.merge();        
        return "redirect:/tier/" + tier.getId();        
    }

	@RequestMapping(value = "/tier/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("tier", Tier.findTier(id));        
        modelMap.addAttribute("rates", Rate.findAllRates());        
        return "tier/update";        
    }

	@RequestMapping(value = "/tier/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        Tier.findTier(id).remove();        
        return "redirect:/tier?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
}
